﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using mp3player;
using mp3reader;


namespace kdp
{
    public partial class playerForm : Form
    {
        Mp3Play mp3 = null;
        ArrayList Files = new ArrayList();
        List<string[]> playList = new List<string[]>();
        string Mp3SrcFile = "";
        bool indexChanged;

        public playerForm()
        {
            InitializeComponent();
        }

        // PLAY/PAUSE
        private void playButton_Click(object sender, EventArgs e)
        {
            if (!mp3.IsPlaying || indexChanged)
            {
                mp3.Filename = Mp3SrcFile;
                mp3.Play();
                indexChanged = false;
            }
            else
            {
                mp3.Pause();
            }
        }

        // FORM LOAD
        private void playerForm_Load(object sender, EventArgs e)
        {
            mp3 = new Mp3Play();
            Byte isNotEmpty = 0;
            int position = 0;

            using (var fs = new FileStream("lastPosition", FileMode.Open, FileAccess.Read))
            {
                using (var sr = new StreamReader(fs, Encoding.GetEncoding(1251)))
                {
                    playList.Clear();
                    playlistListBox.Items.Clear();

                    while (!sr.EndOfStream)
                    {
                        string[] pathElements = sr.ReadLine().Split('|');

                        isNotEmpty = Convert.ToByte(pathElements[0]);
                        Mp3SrcFile = pathElements[1];                          
                        position = Convert.ToInt32(pathElements[2]);
                    }
                }
            }

            if (isNotEmpty == 1)
            {
                using (var fs = new FileStream("defaultPlaylist", FileMode.Open, FileAccess.Read))
                {
                    using (var sr = new StreamReader(fs, Encoding.GetEncoding(1251)))
                    {
                        playList.Clear();
                        playlistListBox.Items.Clear();

                        while (!sr.EndOfStream)
                        {
                            string[] pathElements = sr.ReadLine().Split('|');
                            playList.Add(pathElements);
                            playlistListBox.Items.Add(pathElements[0]);
                            Files.Add(pathElements[1]);
                        }
                    }
                }
                
            playlistListBox.SelectedItem = Path.GetFileNameWithoutExtension(Mp3SrcFile);
                
            if (Mp3SrcFile != "")
            {
                mp3.Filename = Mp3SrcFile;
                mp3.Play();
                mp3.SetPosition(position);
                indexChanged = false;
            }
            }
            
        }

        // STOP
        private void stopButton_Click(object sender, EventArgs e)
        {
            if (mp3.IsPlaying)
            {
                if (mp3.isPaused)
                {
                    mp3.Pause();
                }
                mp3.Stop();
            }
        }

        // OPEN
        private void открытьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            int Counter;
            int itemCounter = playlistListBox.Items.Count;
            ofd.Multiselect = true;
            ofd.Title = "Open";
            ofd.Filter = "MPEG Files(*.mp3)|*.mp3";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    foreach (string fileName in ofd.FileNames)
                    {
                        string shortPath = Path.GetFileName(fileName);
                        shortPath = shortPath.Substring(0, shortPath.Length - 4);

                        string[] pathElements = new string[2];
                        pathElements[0] = shortPath;
                        pathElements[1] = fileName;

                        playList.Add(pathElements);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(@"Error: Could not read file from disk. Original error: " + ex.Message);
                }

                if (playlistListBox.Items.Count != 0)
                {
                    playlistListBox.SelectedIndex = playlistListBox.Items.Count - 1;
                }

                foreach (string Item in ofd.FileNames)
                {
                    Counter = playlistListBox.Items.Count + 1;
                    playlistListBox.Items.Add(Path.GetFileNameWithoutExtension(Item));
                    Files.Add(Item);             
                }

                if (itemCounter != 0)
                {
                    playlistListBox.SelectedIndex = itemCounter;
                }
                else
                {
                    playlistListBox.SelectedIndex = 0;
                }

                if (Mp3SrcFile != "")
                {
                    mp3.Filename = Mp3SrcFile;                  
                    mp3.Play();
                    indexChanged = false;
                }
            }
        }

        // INDEX CHANGED
        private void playlistListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Mp3SrcFile = (string)Files[playlistListBox.SelectedIndex];
                mp3Reader mp3 = new mp3Reader(Mp3SrcFile);
                trackLabel.Text = mp3.Title;
                artistLabel.Text = mp3.Artist;
                albumLabel.Text = "Альбом: " + mp3.Album;
                yearLabel.Text = "Год: " + mp3.Year;
                fileNameLabel.Text = Mp3SrcFile;
                indexChanged = true;
            }
            catch
            {

            }
        }

        // NEXT
        private void nextButton_Click(object sender, EventArgs e)
        {
            int Idx = playlistListBox.SelectedIndex;
            Idx++;

            if (Idx >= playlistListBox.Items.Count)
            {
                Idx = (playlistListBox.Items.Count - 1);
            }
            playlistListBox.SelectedIndex = Idx;
            if (Mp3SrcFile != "")
            {
                mp3.Filename = Mp3SrcFile;
                mp3.Play();
                indexChanged = false;
            }
        }

        // PREV
        private void previousButton_Click(object sender, EventArgs e)
        {
            int Idx = playlistListBox.SelectedIndex;
            Idx--;

            if (Idx <= 0)
            {
                Idx = 0;
            }
            playlistListBox.SelectedIndex = Idx;
            if (Mp3SrcFile != "")
            {
                mp3.Filename = Mp3SrcFile;
                mp3.Play();
                indexChanged = false;
            }
        }

        // PLAY HOTKEY
        private void playerForm_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Space:
                    playButton.PerformClick();
                    break;
                default:
                    break;
            }
        }

        // ADD
        private void addToPlsButton_Click(object sender, EventArgs e)
        {
            открытьToolStripMenuItem_Click(sender, e);
        }

        // DEL
        private void delFromPlsButton_Click(object sender, EventArgs e)
        {
            stopButton_Click(sender, e);
            playlistListBox.Items.Remove(playlistListBox.Items[playlistListBox.SelectedIndex]);
        }

        // EXIT
        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Mp3SrcFile = mp3.Filename;
            string Position = mp3.CurrentPosition.ToString();

            try
            {
                using (var fs = new FileStream("defaultPlaylist", FileMode.Create, FileAccess.Write))
                {
                    using (var sw = new StreamWriter(fs, Encoding.GetEncoding(1251)))
                    {
                        foreach (var song in playList)
                        {
                            string outputString = song[0] + "|" + song[1];
                            sw.WriteLine(outputString);
                        }
                    }
                }

                using (var fs = new FileStream("lastPosition", FileMode.Create, FileAccess.Write))
                {
                    using (var sw = new StreamWriter(fs, Encoding.GetEncoding(1251)))
                    {
                        string outputString = "";
                        if (playlistListBox.Items.Count != 0)
                        {
                            outputString = "1" + "|" + Mp3SrcFile + "|" + Position;
                        }
                        else
                        {
                            outputString = "0" + "|" + Mp3SrcFile + "|" + Position;
                        }
                        sw.WriteLine(outputString);
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(@"Error: Could not read file from disk. Original error: " + ex.Message);
            }          
            Application.Exit();
        }

        // ABOUT
        private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Аудиопроигрыватель «KD Player» \n\nДанная программа предназначена для воспроизведения файлов в формате MP3.\n\n© НИ ТПУ, 2014.\n© Кустов Денис Анатольевич, 2014.", "KD Player - о программе");
        }

        // SAVE PLS
        private void сохранитьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var sourceFileSaveFileDialog = new SaveFileDialog
            {
                InitialDirectory = @"\",
                Filter = @"Playlist Files (*.pls)|*.pls",
                RestoreDirectory = true,
                Title = @"Please select playlist file for saving"
            };

            if (sourceFileSaveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (var fs = new FileStream(sourceFileSaveFileDialog.FileName, FileMode.Create, FileAccess.Write))
                    {
                        using (var sw = new StreamWriter(fs, Encoding.GetEncoding(1251)))
                        {
                            foreach (var song in playList)
                            {
                                string outputString = song[0] + "|" + song[1];
                                sw.WriteLine(outputString);
                            }
                        }
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(@"Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        // OPEN PLS
        private void открытьToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var sourceFileOpenFileDialog = new OpenFileDialog
            {
                InitialDirectory = @"E:\",
                Filter = @"Playlist Files (*.pls)|*.pls",
                RestoreDirectory = true,
                Multiselect = false,
                Title = @"Please select playlist file for opening"
            };

            if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string fileName = sourceFileOpenFileDialog.FileName;

                    using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                    {
                        using (var sr = new StreamReader(fs, Encoding.GetEncoding(1251)))
                        {
                            playList.Clear();
                            playlistListBox.Items.Clear();

                            while (!sr.EndOfStream)
                            {
                                string[] pathElements = sr.ReadLine().Split('|');
                                playList.Add(pathElements);
                                playlistListBox.Items.Add(pathElements[0]);
                                Files.Add(pathElements[1]);
                            }
                        }
                    }

                    if (Mp3SrcFile != "")
                    {
                        mp3.Filename = Mp3SrcFile;
                        mp3.Play();
                        indexChanged = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(@"Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        // FORM CLOSING
        private void playerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            выходToolStripMenuItem_Click(sender, e);
        }
    }
}
